import { Message, MessageBox } from "element-ui";
import util from "@/libs/util.js";
import router from "@/router";
import { UserLogout, UserLogin, sysTokenLogin } from "api/sys";
import { ZwddLogin, ZwddTokenLogin, ZwddQrCodeLogin } from "api/zwdd";
import { DdLogin } from "api/dd";
import { cloneDeep } from "lodash";
import getMenuTree from "libs/getMenuTree";
import getRouterTree from "libs/getRouterTree";

export default {
  namespaced: true,
  actions: {
    /**
     * @description 登录
     * @param {Object} context
     * @param {Object} payload route {Object} 登录成功后定向的路由对象 任何 vue-router 支持的格式
     */
    login({ dispatch }, { params, vm } = {}) {
      return new Promise((resolve, reject) => {
        // 开始请求登录接口
        const { type, ...restParams } = params;
        let loginFn = {
          0: UserLogin,
          1: ZwddLogin,
          2: DdLogin,
          3: ZwddTokenLogin,
          4: sysTokenLogin,
          5: ZwddQrCodeLogin,
        }[type];

        loginFn(restParams)
          .then(async (res) => {
            // 设置 vuex 用户信息
            const {
              userName,
              userMenu,
              organizeId,
              accountId,
              organizeName,
              nickName,
              deptId,
              deptName,
              mobilePhone,
              token,
            } = res;
            util.cookies.set("token", token);
            if (userMenu && userMenu.length) {
              const clonedMenuData = cloneDeep(userMenu);
              const clonedRouterData = cloneDeep(userMenu);

              // 设置菜单数据
              const menuTree = getMenuTree({
                menuData: clonedMenuData,
                vm,
              });
              await dispatch("d2admin/menu/menuSet", menuTree, {
                root: true,
              });

              // 设置路由数据
              const routerTree = getRouterTree({
                routerData: clonedRouterData,
                vm,
              });
              await dispatch("d2admin/router/set", routerTree, {
                root: true,
              });
            }

            // 设置用户信息
            await dispatch(
              "d2admin/user/set",
              {
                name: userName,
                organizeId,
                accountId,
                organizeName,
                deptId,
                deptName,
                nickName,
                mobilePhone,
              },
              { root: true }
            );
            // 用户登录后从持久化数据加载一系列的设置
            await dispatch("load");

            // 结束
            resolve();
          })
          .catch((err) => {
            console.log("err: ", err);
            reject(err);
          });
      });
    },
    /**
     * @description 退出用户并返回登录页面
     * @param {Object} context
     * @param {Object} payload confirm {Boolean} 是否需要确认
     */
    logout({ commit, dispatch }, { confirm = false } = {}) {
      /**
       * @description 退出
       */
      async function logout() {
        try {
          await UserLogout();
          // 删除cookie
          util.cookies.remove("token");
          util.cookies.remove("uuid");
          // 清空 vuex 用户信息
          await dispatch("d2admin/user/set", {}, { root: true });
        } catch (e) {
          console.log(e);
        } finally {
          // 跳转路由
          router.replace({
            name: "login",
          });
        }
      }
      // 判断是否需要确认
      if (confirm) {
        commit("d2admin/gray/set", true, { root: true });
        MessageBox.confirm("确定要退出当前用户吗?", "退出用户", {
          type: "warning",
        })
          .then(() => {
            commit("d2admin/gray/set", false, { root: true });
            logout();
          })
          .catch(() => {
            commit("d2admin/gray/set", false, { root: true });
            Message({
              message: "取消退出操作",
            });
          });
      } else {
        logout();
      }
    },
    /**
     * @description 用户登录后从持久化数据加载一系列的设置
     * @param {Object} context
     */
    async load({ dispatch }) {
      // DB -> store 加载用户名
      await dispatch("d2admin/user/load", null, { root: true });
      // DB -> store 加载主题
      await dispatch("d2admin/theme/load", null, { root: true });
      // DB -> store 加载页面过渡效果设置
      await dispatch("d2admin/transition/load", null, { root: true });
      // DB -> store 持久化数据加载上次退出时的多页列表
      await dispatch("d2admin/page/openedLoad", null, { root: true });
      // DB -> store 持久化数据加载侧边栏折叠状态
      await dispatch("d2admin/menu/asideCollapseLoad", null, { root: true });
      // DB -> store 持久化数据加载菜单
      await dispatch("d2admin/menu/load", null, { root: true });
      // DB -> store 持久化数据加载系统配置信息
      await dispatch("d2admin/sysConfig/load", null, { root: true });
      // DB -> store 持久化数据加载布局样式
      await dispatch("d2admin/layout/load", null, { root: true });
    },
  },
};
